/*jslint vars: true, forin: true, sloppy: true */
/*global probe, angular */
probe.controller("ProjectManagement", function ($scope, $element, ocAPI, ocDialog) {
	var accountDI = ocDialog.queryDI($element);

	$scope.menu = [
		{
			title: '项目(P)',
			menu: [
				{
					title: '新建项目',
					attr: 'oc-dialog-open="projectAdd"'
				}
			]
		}
	];

	$scope.projects = [];
	function listMyProject() {
		ocAPI.use('listMyProject').by().then(function (data) {
			$scope.projects = data.projects;
		});
	}
	$scope.projectAdd = {
		name: 'project/add',
		share: function () {
			return {
				refreshProjectList: $scope.refreshProjectList
			};
		}
	};
	function deleteProjectHandle(projectId) {
		ocAPI.use('deleteProject').by(projectId).then(function () {
			$scope.refreshProjectList();
		});
	}
	$scope.openProject = function (index) {
		ocDialog.getNewDI('project/detail', {
			projectId: $scope.projects[index].projectId,
			refreshProjectList: $scope.refreshProjectList,
			deleteProject: deleteProjectHandle
		}).then(function (DI) {
			DI.openDialogFrom(accountDI);
		});
	};

	$scope.refreshProjectList = function () {
		ocAPI.cache.remove('MY_PROJECT_LIST');
		listMyProject();
	};

	$scope.deleteProject = function (index, event) {
		var projectId = $scope.projects[index].projectId;
		event.stopPropagation();
		var alert = {
			title: '删除项目',
			message: '删除项目会导致项目内所有资源一并删除\n且无法恢复，您确定吗？',
			callFn: function () {
				deleteProjectHandle(projectId);
			}
		};
		ocDialog.alert(alert, accountDI);
	};

	//init
	listMyProject();
});
